package com.sicau.socialpracticesystem.util;

import org.springframework.util.StringUtils;

import java.security.MessageDigest;

/**
 * MD5加密工具
 */
public class MD5Util {

    /**
     * 默认盐值
     */
    public static final String DEFAULT_SALT = "sxt";

    public static String encode(String password) {
        return encode(password, null);
    }

    public static String encode(String password, String salt) {
        if (StringUtils.isEmpty(salt)) {
            salt = DEFAULT_SALT;
        }
        password = password + salt;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = password.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

//    public static void main(String[] args) {
//        System.out.println(MD5Util.encode("123", "ttxxi"));
//    }

}